#include "motor_drivers.hpp"

class EmptyLogContentError : public std::runtime_error {
public:
    EmptyLogContentError() : std::runtime_error("No content to write to log file") {}
};

class FailedOpenFile : public std::runtime_error{
    public:
        explicit FailedOpenFile(const std::string& logfile) : std::runtime_error("Failed to open log file: " + logfile){}
};

MotorDrivers::log::log(const std::string& logName, const std::string& logPath): 
    logName_(logName), logPath_(logPath){
        
    std::filesystem::path dir(logPath_);
    dir.remove_filename();
    std::filesystem::create_directories(dir);
    logFile_.open(logPath_ + logName_, std::ios::out | std::ios::trunc);
    if (!logFile_.is_open()) {
        throw FailedOpenFile(logPath_ + logName_);
    }
}

void MotorDrivers::log::logWrite(const std::string& logContent){
    if (logContent.empty()) {
        throw EmptyLogContentError();
    }
    logFile_ << logContent << std::endl;
    logFile_.flush();
}

void MotorDrivers::log::logWriteTimestamp(){
    logFile_ << std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>
        (std::chrono::system_clock::now().time_since_epoch()).count()) << std::endl;
    logFile_.flush();
}